package com.lancoo.klgcourseware.presenter;

import android.content.Context;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.lancoo.klgcourseware.api.KlgEnglishApi;
import com.lancoo.klgcourseware.base.BaseKlgPresenter;
import com.lancoo.klgcourseware.entity.ChineseMeaning;
import com.lancoo.klgcourseware.entity.ESPCardSource;
import com.lancoo.klgcourseware.entity.EnglishCardSource;
import com.lancoo.klgcourseware.entity.EnglishCardUsageTrain;
import com.lancoo.klgcourseware.entity.ExpressionAndUsageModel;
import com.lancoo.klgcourseware.entity.KlgApiResponse;
import com.lancoo.klgcourseware.entity.ObsConfigMsgBean;
import com.lancoo.klgcourseware.entity.ResourcePlatFormConfigure;
import com.lancoo.klgcourseware.entity.WordCodeResponce;
import com.lancoo.klgcourseware.entity.WordExplainModel;
import com.lancoo.klgcourseware.entity.bean.ErrorStates;
import com.lancoo.klgcourseware.entity.bean.KlgCommonBean;
import com.lancoo.klgcourseware.entity.bean.KlgDbConstant;
import com.lancoo.klgcourseware.utils.UniCodeUtils;
import com.lancoo.klgcourseware.utils.klog.KLog;
import com.lancoo.klgcourseware.view.IKnowledgeEnglishView;

import java.util.List;

import io.reactivex.disposables.Disposable;
import lancoo.com.net.retrofitrxjava.NetworkTransformer;
import lancoo.com.net.retrofitrxjava.RxApiManager;
import lancoo.com.net.retrofitrxjava.network.Network;
import lancoo.com.net.retrofitrxjava.subscriber.NormalSubscriber;

/**
 * Created by pengmi on 2018/11/7.
 * Description:英语学科知识点卡片处理器
 */

public class KnowledgeEnglishPresenter extends BaseKlgPresenter {

    private static final String TAG = "KnowledgeEnglishPresent";

    private IKnowledgeEnglishView iEnglishCardStudyView;
        private final String classicSenAdd="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
    private boolean enableExpandTrain;

    public KnowledgeEnglishPresenter(Context mContext, IKnowledgeEnglishView iEnglishCardStudyView) {
        super(mContext);
        this.iEnglishCardStudyView=iEnglishCardStudyView;
    }


    public void requestInfo(String klgCode){
        iEnglishCardStudyView.showLoadingPg();
        getVersionControl(klgCode);
    }

    public void getWordCode(String content){
        Log.e("aaaaaa","");
        iEnglishCardStudyView.showLoadingPg();
        RxApiManager.getInstance().cancelByTag(TAG);
        Disposable disposable = Network.getJsonData(KlgEnglishApi.class, KlgDbConstant.klgPublicUrl)
                .getWordCode(content)
                .compose(NetworkTransformer.<WordCodeResponce>commonSchedulers())
                .subscribeWith(new NormalSubscriber<WordCodeResponce>(){

                    @Override
                    public void onNext(WordCodeResponce s) {
                        super.onNext(s);
                        if(s!=null&&s.getStatus()==1&&s.getData()!=null&&s.getData().size()>0){
                            requestInfo(s.getData().get(0));
                        }else{
//                            iKlgCourseWareView.loadingFailure(ErrorStates.EMPTYDATA);
                            iEnglishCardStudyView.loadingSuccess(null, LoadStatus.REFRESH);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
//                        iKlgCourseWareView.loadingFailure(ErrorStates.EMPTYDATA);
                        iEnglishCardStudyView.loadingSuccess(null, LoadStatus.REFRESH);
                    }
                });
        RxApiManager.getInstance().add(TAG,disposable);
    }


    private void getVersionControl(final String klgCode){
        Disposable disposable=Network.getJsonData(KlgEnglishApi.class, KlgDbConstant.klg_baseUrl).getKlgVersion().compose(NetworkTransformer.<String>commonSchedulers()).
                subscribeWith(new NormalSubscriber<String>(){
                    @Override
                    public void onNext(String stringKlgApiResponse) {
                        super.onNext(stringKlgApiResponse);
                        Log.e("aaaaaaaa","onNext:"+stringKlgApiResponse);
                        if(TextUtils.equals("v5.4",stringKlgApiResponse)){
                            getKnowledgeConfigMsg(klgCode);
                        }else{
                            getV56VersionConfigMsg(klgCode);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        Log.e("aaaaaaaa","onError:"+e.toString());
                        getKnowledgeConfigMsg(klgCode);
//                        iEnglishCardStudyView.loadingFailure(ErrorStates.NETERROR);
                    }
                });
        RxApiManager.getInstance().add(TAG,disposable);
    }

    private void getV56VersionConfigMsg(final String klgCode){
        Disposable disposable=Network.getJsonData(KlgEnglishApi.class, KlgDbConstant.klg_baseUrl).getObsConfig().compose(NetworkTransformer.<ObsConfigMsgBean>commonSchedulers()).
                subscribeWith(new NormalSubscriber<ObsConfigMsgBean>(){
                    @Override
                    public void onNext(ObsConfigMsgBean stringKlgApiResponse) {
                        super.onNext(stringKlgApiResponse);
                        if(stringKlgApiResponse!=null){
                            KlgDbConstant.mediaUrl="http://"+stringKlgApiResponse.getBucketName()+"."+stringKlgApiResponse.getEndpoint()+"/";
                            checkHasBasicTrainData(klgCode);
                        }else{
                            getKnowledgeConfigMsg(klgCode);
//                            iEnglishCardStudyView.loadingFailure(ErrorStates.DATAERROR);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        getKnowledgeConfigMsg(klgCode);
                        Log.e("aaaaaa","getV56VersionConfigMsg");
//                        iEnglishCardStudyView.loadingFailure(ErrorStates.NETERROR);
                    }
                });
        RxApiManager.getInstance().add(TAG,disposable);
    }

    private void getKnowledgeConfigMsg(final String klgCode){

        Disposable disposable=Network.getJsonData(KlgEnglishApi.class, KlgDbConstant.klg_baseUrl).getPlatFormConfigure().compose(NetworkTransformer.<KlgApiResponse<ResourcePlatFormConfigure>>commonSchedulers()).
                subscribeWith(new NormalSubscriber<KlgApiResponse<ResourcePlatFormConfigure>>(){
                    @Override
                    public void onNext(KlgApiResponse<ResourcePlatFormConfigure> stringKlgApiResponse) {
                        super.onNext(stringKlgApiResponse);
                        if(stringKlgApiResponse.getState()==1){
                            if(TextUtils.isEmpty( KlgDbConstant.mediaUrl)){
                                KlgDbConstant.mediaUrl="http://"+stringKlgApiResponse.getData().getHttpIP()+":"+stringKlgApiResponse.getData().getHttpPort()+"/";
                            }else{
                                if(!TextUtils.equals("/", KlgDbConstant.mediaUrl.substring( KlgDbConstant.mediaUrl.length()-1))){
                                    KlgDbConstant.mediaUrl=  KlgDbConstant.mediaUrl+"/";
                                }
                            }
                            checkHasBasicTrainData(klgCode);
                        }else{
                            iEnglishCardStudyView.loadingFailure(ErrorStates.DATAERROR);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        iEnglishCardStudyView.loadingFailure(ErrorStates.NETERROR);
                    }
                });
        RxApiManager.getInstance().add(TAG,disposable);
    }

    private void checkHasBasicTrainData(final String klgCode){
        if(!TextUtils.isEmpty(klgCode)&&klgCode.length()>2&&TextUtils.equals("G",klgCode.substring(klgCode.length()-2,klgCode.length()-1))){
            Log.e("aaaaaaa","ESPESPESPESPESPESPESP");
            getKnowledgeESPCardMsg(klgCode);
            return;
        }
        Disposable disposable=Network.getJsonData(KlgEnglishApi.class, KlgDbConstant.klg_baseUrl).getEnglishPractice(klgCode).compose(NetworkTransformer.<KlgApiResponse<EnglishCardUsageTrain>>commonSchedulers())
                .subscribeWith(new NormalSubscriber<KlgApiResponse<EnglishCardUsageTrain>>(){

                    @Override
                    public void onNext(KlgApiResponse<EnglishCardUsageTrain> englishCardUsageTrainKlgApiResponse) {
                        super.onNext(englishCardUsageTrainKlgApiResponse);

                        if(englishCardUsageTrainKlgApiResponse.getState()==1&&englishCardUsageTrainKlgApiResponse.getData()!=null){
                            if(englishCardUsageTrainKlgApiResponse.getData().getWordSenList()!=null&&englishCardUsageTrainKlgApiResponse.getData().getWordSenList().size()>0&&
                                    englishCardUsageTrainKlgApiResponse.getData().getWordSenList().get(0).getHideWordList()!=null&&englishCardUsageTrainKlgApiResponse.getData().getWordSenList().get(0).getHideWordList().size()>0){
                                enableExpandTrain=true;
                            }else if(englishCardUsageTrainKlgApiResponse.getData().getExpressSenList()!=null&&englishCardUsageTrainKlgApiResponse.getData().getExpressSenList().size()>0){
                                enableExpandTrain=true;
                            }else if(englishCardUsageTrainKlgApiResponse.getData().getSyntaxSenList()!=null&&englishCardUsageTrainKlgApiResponse.getData().getSyntaxSenList().size()>0){
                                enableExpandTrain=true;
                            }else{
                                enableExpandTrain=false;
                            }

                        }else{
                            enableExpandTrain=false;
                        }
                        getKnowledgeESPCardMsg(klgCode);
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        enableExpandTrain=false;
                        getKnowledgeESPCardMsg(klgCode);
                    }
                });
        RxApiManager.getInstance().add(TAG,disposable);
    }


    private void getKnowledgeESPCardMsg(final String klgCode){
        Disposable disposable=Network.getJsonData(KlgEnglishApi.class,KlgDbConstant.klg_baseUrl).getESPMaterialCardByCode(klgCode).compose(NetworkTransformer.<KlgApiResponse<ESPCardSource>>commonSchedulers()).
                subscribeWith(new NormalSubscriber<KlgApiResponse<ESPCardSource>>(){
                    @Override
                    public void onNext(KlgApiResponse<ESPCardSource> englishCardSourceKlgApiResponse) {
                        super.onNext(englishCardSourceKlgApiResponse);
                        KLog.json(new Gson().toJson(englishCardSourceKlgApiResponse));
                        if(englishCardSourceKlgApiResponse.getState()==1){
                            enableExpandTrain=true;
                            iEnglishCardStudyView.loadingSuccess(buildCommonBean(englishCardSourceKlgApiResponse.getData()), LoadStatus.REFRESH);
                        }else{
                            getKnowledgeNewCardMsg(klgCode);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        getKnowledgeNewCardMsg(klgCode);
                    }
                });
        RxApiManager.getInstance().add(TAG,disposable);
    }

    private void getKnowledgeNewCardMsg(final String klgCode){
        Disposable disposable=Network.getJsonData(KlgEnglishApi.class,KlgDbConstant.klg_baseUrl).getEnglishCardByCode(klgCode).compose(NetworkTransformer.<KlgApiResponse<EnglishCardSource>>commonSchedulers()).
                subscribeWith(new NormalSubscriber<KlgApiResponse<EnglishCardSource>>(){
                    @Override
                    public void onNext(KlgApiResponse<EnglishCardSource> englishCardSourceKlgApiResponse) {
                        super.onNext(englishCardSourceKlgApiResponse);
                        KLog.json(new Gson().toJson(englishCardSourceKlgApiResponse));
                        if(englishCardSourceKlgApiResponse.getState()==1||englishCardSourceKlgApiResponse.getState()==0){
                            iEnglishCardStudyView.loadingSuccess(buidKlgCommonEntity(englishCardSourceKlgApiResponse.getData()), LoadStatus.REFRESH);
                        }else{
                            getKnowledgeCardMsg(klgCode);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        getKnowledgeCardMsg(klgCode);
                    }
                });
        RxApiManager.getInstance().add(TAG,disposable);
    }

    private void getKnowledgeCardMsg(String klgCode){
        Disposable disposable=Network.getJsonData(KlgEnglishApi.class,KlgDbConstant.klg_baseUrl).getEnglishOldCardByCode(klgCode).compose(NetworkTransformer.<KlgApiResponse<EnglishCardSource>>commonSchedulers()).
                subscribeWith(new NormalSubscriber<KlgApiResponse<EnglishCardSource>>(){
                    @Override
                    public void onNext(KlgApiResponse<EnglishCardSource> englishCardSourceKlgApiResponse) {
                        super.onNext(englishCardSourceKlgApiResponse);
                        KLog.json(new Gson().toJson(englishCardSourceKlgApiResponse));
                        if(englishCardSourceKlgApiResponse.getState()==1||englishCardSourceKlgApiResponse.getState()==0){
                            iEnglishCardStudyView.loadingSuccess(buidKlgCommonEntity(englishCardSourceKlgApiResponse.getData()), LoadStatus.REFRESH);
                        }else{
                            iEnglishCardStudyView.loadingFailure(ErrorStates.DATAERROR);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        iEnglishCardStudyView.loadingFailure(ErrorStates.NETERROR);
                    }
                });
        RxApiManager.getInstance().add(TAG,disposable);
    }


    /**
     * 构造知识点课件数据公共模型
     * @param cardSource
     * @return
     */
    private KlgCommonBean buidKlgCommonEntity(EnglishCardSource cardSource){
        if(cardSource==null){
            return null;
        }
        KlgCommonBean klgCommonBean=new KlgCommonBean();
        klgCommonBean.setKlgCode(cardSource.getKlgCode());
        klgCommonBean.setKlgName(cardSource.getKlgName());
        klgCommonBean.setKlgType(cardSource.getKlgType());
        if(cardSource.getWordData()!=null){
            klgCommonBean.setUn_phonetic(UniCodeUtils.convertToChinese(cardSource.getWordData().getUN_phonetic()));
            if(!TextUtils.isEmpty(cardSource.getWordData().getUN_voice())){
                klgCommonBean.setUn_voice( KlgDbConstant.mediaUrl+cardSource.getWordData().getUN_voice());
            }
            klgCommonBean.setUs_phonetic(UniCodeUtils.convertToChinese(cardSource.getWordData().getUS_phonetic()));
            if(!TextUtils.isEmpty(cardSource.getWordData().getUS_voice())){
                klgCommonBean.setUs_voice(KlgDbConstant.mediaUrl+cardSource.getWordData().getUS_voice());
            }
            if(TextUtils.equals("ESP",cardSource.getKlgType())){
                klgCommonBean.setClassicSen(cardSource.getWordData().getClassicSen());
                if(cardSource.getWordData().getExplainList()!=null&&cardSource.getWordData().getExplainList().size()>5){
                    klgCommonBean.setShowMoreMeaning(true);
                    klgCommonBean.setShortExplan(buildExplainString(cardSource.getWordData().getExplainList(),false));
                }else{
                    klgCommonBean.setShowMoreMeaning(false);
                }
            }else{
                klgCommonBean.setClassicSen(buildNewClassicSenString(cardSource.getWordData().getClassicSen()));
            }
            klgCommonBean.setClassicTrain(""+Html.fromHtml(cardSource.getWordData().getClassicTran()));
            if(!TextUtils.isEmpty(cardSource.getWordData().getClassicVoice())){
                klgCommonBean.setClassicVoice(KlgDbConstant.mediaUrl+cardSource.getWordData().getClassicVoice());
            }
            klgCommonBean.setExplain(buildExplainString(cardSource.getWordData().getExplainList(),true));

        }
        if(cardSource.getExpressionData()!=null&&cardSource.getExpressionData().getUsageList()!=null&&cardSource.getExpressionData().getUsageList().size()>0){
//            klgCommonBean.setExplain(cardSource.getExpressionData().getUsageList().get(0).getExplain().trim());
//            klgCommonBean.setUsage(cardSource.getExpressionData().getUsageList().get(0).getUsage());
            if(cardSource.getExpressionData().getUsageList()!=null&&cardSource.getExpressionData().getUsageList().size()>0){
                StringBuilder stringBuilder=new StringBuilder();
                for (ExpressionAndUsageModel expressionAndUsageModel:cardSource.getExpressionData().getUsageList()){
                    stringBuilder.append(expressionAndUsageModel.getUsage());
                    stringBuilder.append("\n");
                }
                klgCommonBean.setUsage(stringBuilder.toString());
            }
            if(cardSource.getExpressionData().getUsageList()!=null&&cardSource.getExpressionData().getUsageList().size()>0){
                StringBuilder stringBuilder=new StringBuilder();
                for (ExpressionAndUsageModel expressionAndUsageModel:cardSource.getExpressionData().getUsageList()){
                    stringBuilder.append(expressionAndUsageModel.getExplain().trim());
                    stringBuilder.append("\n");
                }
                klgCommonBean.setExplain(stringBuilder.toString());
            }
        }
        if(cardSource.getSyntaxData()!=null){
            if(!TextUtils.isEmpty(cardSource.getSyntaxData().getClassicSen())){
                klgCommonBean.setClassicSen(buildNewClassicSenString(cardSource.getSyntaxData().getClassicSen()));
            }

            klgCommonBean.setClassicTrain(""+Html.fromHtml(cardSource.getSyntaxData().getClassicTran()));
            klgCommonBean.setParaphrase(cardSource.getSyntaxData().getThemeName());
            if(!TextUtils.isEmpty(cardSource.getSyntaxData().getClassicVoice())){
                klgCommonBean.setClassicVoice(KlgDbConstant.mediaUrl+cardSource.getSyntaxData().getClassicVoice());
            }
            if(cardSource.getSyntaxData().getUsageList()!=null&&cardSource.getSyntaxData().getUsageList().size()>0){
                StringBuilder stringBuilder=new StringBuilder();
                for (ExpressionAndUsageModel expressionAndUsageModel:cardSource.getSyntaxData().getUsageList()){
                    stringBuilder.append(expressionAndUsageModel.getUsage());
                    stringBuilder.append("\n");
                }
                klgCommonBean.setUsage(stringBuilder.toString());
            }
        }

        return klgCommonBean;
    }

    private KlgCommonBean buildCommonBean(ESPCardSource espCardSource){

        KlgCommonBean klgCommonBean=new KlgCommonBean();
        klgCommonBean.setKlgCode(espCardSource.getKlgCode());
        klgCommonBean.setKlgName(espCardSource.getKlgName());
        klgCommonBean.setKlgType("ESP");
        klgCommonBean.setUn_voice(KlgDbConstant.mediaUrl+espCardSource.getUN_voice());
        klgCommonBean.setUn_phonetic(UniCodeUtils.convertToChinese(espCardSource.getUN_phonetic()));
        klgCommonBean.setUs_voice(KlgDbConstant.mediaUrl+espCardSource.getUS_voice());
        klgCommonBean.setUs_phonetic(UniCodeUtils.convertToChinese(espCardSource.getUS_phonetic()));
        klgCommonBean.setClassicSen(espCardSource.getPicturePath());
        klgCommonBean.setExplain(buildESPExplainString(espCardSource.getMeaningList(),true));
        klgCommonBean.setMeaningTime(espCardSource.getMeaningTime());
        klgCommonBean.setEnglishMeaning(espCardSource.getEnglishMeaning());
        klgCommonBean.setMeaningVoice(espCardSource.getMeaningVoice());
        if(espCardSource.getMeaningList()!=null&&espCardSource.getMeaningList().size()>5){
            klgCommonBean.setShowMoreMeaning(true);
            klgCommonBean.setShortExplan(buildESPExplainString(espCardSource.getMeaningList(),false));
        }else{
            klgCommonBean.setShowMoreMeaning(false);
        }
        if(TextUtils.isEmpty(espCardSource.getMeaningVoice())){
            enableExpandTrain=false;
        }
        return klgCommonBean;

    }


    /**
     * 构造释义内容
     * @param explainModelList
     * @return
     */
    private String buildExplainString(List<WordExplainModel> explainModelList,boolean max){
        StringBuffer explainString=new StringBuffer();
        int index=0;
        if(explainModelList!=null){
            for (WordExplainModel wordExplainModel:explainModelList){
                explainString.append(""+wordExplainModel.getCxAndExplain());
                if(index!=explainModelList.size()-1){
                    explainString.append("<br/>");
                }
                index++;
                if(!max&&index==5){
                    break;
                }
            }
            return Html.fromHtml(explainString.toString()).toString().trim();
        }else {
            return "";
        }
    }


    /**
     * 构造释义内容
     * @param explainModelList
     * @return
     */
    private String buildESPExplainString(List<ChineseMeaning> explainModelList, boolean max){
        StringBuffer explainString=new StringBuffer();
        int index=0;
        if(explainModelList!=null){
            for (ChineseMeaning wordExplainModel:explainModelList){
                explainString.append(""+wordExplainModel.getChineseMeaning());
                if(index!=explainModelList.size()-1){
                    explainString.append("<br/>");
                }
                index++;
                if(!max&&index==5){
                    break;
                }
            }
            return Html.fromHtml(explainString.toString()).toString().trim();
        }else {
            return "";
        }
    }



    private String buildNewClassicSenString(String classicSen){
        if (TextUtils.isEmpty(classicSen)) {
            return classicSen;
        }
        String newString=classicSen.replaceAll("</STRONG>","</font>")
                .replaceAll("<STRONG>","<font color='#0077f0'>")
                .replaceAll("</strong>","</font>")
                .replaceAll("<strong>","<font color='#0077f0'>");
        return newString.trim();
    }

    public boolean isEnableExpandTrain() {
        return enableExpandTrain;
    }

    public void cancelConnection(){
        RxApiManager.getInstance().cancelByTag(TAG);
    }
}
